'''
paramiko模块

> pip install paramiko==3.0.0
> pip uninstall cryptography==43.0.0
> pip install cryptography==36.0.2

作用：实现ssh功能
1、执行远程命令,       ssh root@1.1.1.1 ntpdate
2、文件上传、下载      scp
'''

import paramiko

# 执行远程命令
# def execCMD():
#     ssh_client = paramiko.SSHClient()
#     ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
#     ssh_client.connect(hostname="192.168.140.10", username="root", password="redhat", port=22)
#
#     # 按顺序给返回3个文件， 标准输入、标准输出、标准错误输出
#     stdin, stdout, stderr = ssh_client.exec_command("lsblk")
#     result = stdout.read().decode(encoding="UTF-8")
#     print(result)
#
#     ssh_client.close()
#
# if __name__ == '__main__':
#     execCMD()



print("-----------------------------" * 5)


import paramiko
import sys
import pymysql

# 从数据库获取服务器的连接信息
def get_server_info_from_DB():
    try:
        dbconn = pymysql.connect(host="192.168.1.133", user="admin", password="WWW.1.com", database="it")
    except Exception as e:
        print("数据库连接失败")
        sys.exit()
    cr = dbconn.cursor()

    query_sql = "select ip, name, password, port from user"
    cr.execute(query_sql)
    servers = cr.fetchall()

    cr.close()
    dbconn.close()

    return servers

# 执行命令的操作
def execCMD(ip, name, password, command, port=22):
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
    try:
        ssh_client.connect(hostname=ip, username=name, password=password, port=port)
    except Exception as e:
        print("主机[%s]ssh连接失败" % ip)
        print(e)
        sys.exit()
    stdin, stdout, stderr = ssh_client.exec_command(command)
    result = stdout.read().decode(encoding="UTF-8")
    print(result)

    ssh_client.close()

# 批量执行命令
def MultiExecCMD():
    cmd = input("执行的操作: ").strip()

    servers = get_server_info_from_DB()
    for ip, name, password, port in servers:
        print("主机【%s】执行【%s】操作结果展示: " % (ip, cmd))
        execCMD(ip=ip, name=name, password=password, port=port, command=cmd)
        print("-----------" * 8)


if __name__ == '__main__':
    MultiExecCMD()
